import axios from "axios";
import { AxiosRequestConfig, AxiosResponse } from "axios";

const { VITE_API_URL } = import.meta.env;
// VITE_API_URL 此时开发环境和生产环境都是 /api
// 开发时有代理服务器,打包后直接由服务器渲染(同源)。所以不会有跨域的问题
const http = axios.create({
    baseURL: VITE_API_URL,
    timeout: 5000
});

// 请求拦截
http.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        console.log(config.proxy);
        // 判断有无token
        return config;
    },
    (error) => {
        console.log("interceptors.request", error);
    }
);
// 响应拦截
http.interceptors.response.use(
    (res: AxiosResponse) => {
        // status === 200
        // 判断code码 做出对应操作
        return Promise.resolve(res.data);
    },
    (error) => {
        console.log("interceptors.response", error);
        // status !== 200
        return Promise.reject(error);
    }
);

export const $POST = http.post;
export const $GET = http.get;
export const $PUT = http.put;
export const $DELETE = http.delete;
export default http;
